import {
  batchconvert,
  deleteDevelopingApi,
  importDevelopUserList,
  importRentUserList,
} from '@/services/api';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { useUnmount, useWebSocket } from 'ahooks';
import { Alert, Drawer, Modal, Result, Spin, Upload, message } from 'antd';
import { useEffect, useState } from 'react';
import MonacoEditor from 'react-monaco-editor';
import handover from './Image/handover.png';
import leijifazhanyonghu from './Image/leijifazhanyonghu.png';
import qingkongshujuPng from './Image/qingkongshuju.png';
import yonghushangchuan from './Image/yonghushangchuan.png';

const UploadPage = () => {
  /* 上传loading */
  const [loading, setLoading] = useState(false);

  const [loading2, setLoading2] = useState(false);

  const [loading3, setLoading3] = useState(false);

  const [modal, contextHolder] = Modal.useModal();

  const [isModalOpen, setIsModalOpen] = useState(false);

  const { initialState } = useModel('@@initialState');

  const { info } = initialState || {};

  console.log('info', info);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const { latestMessage, disconnect, connect } = useWebSocket(
    `ws://159.75.207.157:8712/user${info?.user?.id}`,
    {
      onClose: () => {
        console.log('连接断开了');
      },
    },
  );

  useUnmount(() => {
    disconnect();
  });

  const [logValues, setLogValues] = useState(
    `/* \n 批量渠道转个人任务进行中，请耐心等待... \n*/\n`,
  );

  useEffect(() => {
    if (!latestMessage) return;
    setLogValues(logValues + latestMessage?.data + '\n');
  }, [latestMessage]);

  const handleCancel = () => {
    modal.confirm({
      title:
        '确认要关闭当前日志吗?关闭后将无法再次打开，请确认上传没有问题后再关闭！',
      icon: <ExclamationCircleFilled />,

      onOk() {
        setIsModalOpen(false);
        setLogValues(`/* \n 批量渠道转个人任务进行中，请耐心等待... \n*/\n`);
        setTimeout(() => {
          connect();
        }, 500);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  /* 是否正在删除数据 */
  const [isDeleting, setIsDeleting] = useState(false);

  return (
    <>
      <Alert
        size
        style={{ width: '75%', marginBottom: 12, marginTop: 12 }}
        message="批量导入数据，请点击对应的按钮进行操作，导入成功后，请到对应清单验证结果！"
        type="warning"
      />
      <ProCard
        gutter={8}
        bodyStyle={{
          padding: 0,
        }}
      >
        {contextHolder}

        <ProCard
          colSpan={6}
          bodyStyle={{
            padding: 0,
          }}
          bordered
        >
          <Upload.Dragger
            key="upload"
            accept=".xlsx,.xls"
            showUploadList={false}
            beforeUpload={async (file) => {
              try {
                setLoading(true);
                await importDevelopUserList({ file: file });

                setLoading(false);

                // message.success('上传成功');
                modal.info({
                  title: '发展用户上传结果!',
                  icon: null,
                  width: 380,
                  content: <Result status="success" title="上传成功!" />,
                });
              } catch (error) {
                setLoading(false);
              }

              return false;
            }}
          >
            <Spin spinning={loading}>
              <p className="ant-upload-drag-icon">
                <img
                  style={{
                    width: 100,
                    height: 100,
                  }}
                  src={leijifazhanyonghu}
                  alt=""
                />
              </p>
              <p className="ant-upload-text">上传发展用户</p>
            </Spin>
          </Upload.Dragger>
        </ProCard>

        <ProCard
          bodyStyle={{
            padding: 0,
          }}
          colSpan={6}
          bordered
        >
          <Upload.Dragger
            key="upload"
            accept=".xlsx,.xls"
            showUploadList={false}
            beforeUpload={async (file) => {
              try {
                setLoading2(true);
                await importRentUserList({ file: file });
                setLoading2(false);
                // message.success('上传成功');
                modal.info({
                  title: '全量用户上传结果!',
                  icon: null,
                  width: 380,
                  content: <Result status="success" title="上传成功!" />,
                });
              } catch (error) {
                setLoading2(false);
              }

              return false;
            }}
          >
            <Spin spinning={loading2}>
              <p className="ant-upload-drag-icon">
                <img
                  style={{
                    width: 100,
                    height: 100,
                  }}
                  src={yonghushangchuan}
                  alt=""
                />
              </p>
              <p className="ant-upload-text">上传全量用户</p>
            </Spin>
          </Upload.Dragger>
        </ProCard>

        <ProCard
          bodyStyle={{
            padding: 0,
          }}
          colSpan={6}
          bordered
        >
          <Upload.Dragger
            key="upload"
            accept=".xlsx,.xls"
            showUploadList={false}
            beforeUpload={async (file) => {
              try {
                setLoading3(true);
                const { msg } = await batchconvert({
                  file: file,
                  name: `user${info?.user?.id}`,
                });

                showModal();

                setLoading3(false);
                message.success(msg ?? '上传成功');
              } catch (error) {
                setLoading3(false);
              }

              return false;
            }}
          >
            <p className="ant-upload-drag-icon">
              <img
                style={{
                  width: 100,
                  height: 100,
                }}
                src={handover}
                alt=""
              />
            </p>
            <p className="ant-upload-text">批量渠道转个人</p>
          </Upload.Dragger>
        </ProCard>

        <ProCard
          style={{
            background: 'rgba(0, 0, 0, 0.02)',
            // paddingTop: 5,
            /* 鼠标画上去显示手指 */
            cursor: 'pointer',
          }}
          bodyStyle={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          }}
          colSpan={6}
          bordered
        >
          <Spin spinning={isDeleting}>
            <div
              onClick={async () => {
                try {
                  Modal.confirm({
                    title: '提示！！！',
                    content: <div>确认清空全量数据吗？</div>,
                    async onOk() {
                      setIsDeleting(true);
                      await deleteDevelopingApi();
                      message.success('清空成功');
                      setIsDeleting(false);
                    },
                    onCancel() {
                      // message.info('取消清空');
                    },
                  });
                } catch (error) {
                  setIsDeleting(false);
                }
              }}
              className="sdfasdfasfd"
              style={{
                width: '100%',
                height: 145,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                flexDirection: 'column',
              }}
            >
              <p className="ant-upload-drag-icon">
                <img
                  style={{
                    width: 100,
                    height: 100,
                  }}
                  src={qingkongshujuPng}
                  alt=""
                />
              </p>
              <p
                className="ant-upload-text"
                style={{
                  fontSize: 16,
                  marginBottom: 0,
                }}
              >
                清空数据
              </p>
            </div>
          </Spin>
        </ProCard>
      </ProCard>

      <Spin
        tip="批量渠道转个人文件上传中..."
        delay={300}
        spinning={loading3}
        fullscreen
      ></Spin>

      {isModalOpen && (
        <Drawer
          width={800}
          title="批量转换日志"
          open={isModalOpen}
          onClose={handleCancel}
          destroyOnClose
          loading={loading3}
        >
          <MonacoEditor
            language="json"
            theme="vs"
            value={JSON.parse(JSON.stringify(logValues, null, 2))}
            options={{
              readOnly: true,
              automaticLayout: true, // 自动布局
              theme: 'vs', // 官方自带三种主题vs, hc-black, or vs-dark
              foldingStrategy: 'indentation', // 代码可分小段折叠
            }}
          />
        </Drawer>
      )}
    </>
  );
};

export default UploadPage;
